package test.demo;

import cn.hutool.core.util.ArrayUtil;
import tech.waterism.modelbase.PredictBase;
import tech.waterism.modelbase.PredictResult;
import com.alibaba.fastjson.JSON;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 河道汇流单位线（经验单位线）
 *
 * @author 潘晓健
 * @version 1.0
 */

public class UH_C extends PredictBase {

    /**
     * 流域基流
     */
    private double Qbasic;

    /**
     * 单位线序号
     */
    private int unitLineNo;

    /**
     * 单位线长度
     */
    private int unitLineLength;

    /**
     * 单位线
     */
    private double[] unitLine;

    /**
     * 降水时间
     */
    private Date[] floodTm;

    /**
     * 预报开始时间
     */
    private Date startTm;

    /**
     * 预报开始数组下标
     */
    private int startIndex;

    /**
     * 降水序列长度
     */
    private Integer floodRainRange;

    /**
     * 降水时段长
     */
    private double timeInterval;

    /**
     * 上游断面流量过程
     */
    private double[] Q;

    public UH_C(Map<String, String> data) {
        super();
        Qbasic = Double.parseDouble(data.get("Qbasic"));
        floodTm = JSON.parseObject(data.get("dt"), Date[].class);               // input[i].data.dt
        startTm  = JSON.parseObject(data.get("start"), Date.class);
        startIndex = ArrayUtil.indexOf(floodTm, startTm);
        Q = JSON.parseObject(data.get("q"), double[].class);      // input[i].data.q
        unitLineNo = Integer.parseInt(data.get("unitLineNo"));                  // line 3 -------> line X
        unitLineLength = Integer.parseInt(data.get("unitLineLength"));          // line X + 1
        unitLine = JSON.parseObject(data.get("unitLine"), double[].class);      // line X + 2
        timeInterval = Double.parseDouble(data.get("clen"));                    // index.clen
        floodRainRange = Q.length;
    }


    /**
     * 模型计算
     */
    public Map<String, double[]> UHBmodel() {

        // 单位线
        double[] QSim = UnitLine();

        Map<String, double[]> simulationResult = new HashMap<>();
        simulationResult.put("Q", Q);
        simulationResult.put("QSim", QSim);
        return simulationResult;
    }

    /**
     * 单位线
     *
     * @return
     */
    private double[] UnitLine() {
        double[] QSim = new double[floodRainRange];

        for (int i = startIndex; i < floodRainRange; i++) {
            for (int j = 0; j < unitLine.length; j++) {
                if (i + j < floodRainRange) {
                    QSim[j + i] = QSim[j + i] + Q[i] * unitLine[j];
                }
            }
        }

        for (int k = 0; k < floodRainRange; k++) {
            QSim[k] += Qbasic;
        }

        return QSim;
    }

    @Override
    public void init() {

    }

    @Override
    public PredictResult predict() {
        PredictResult result = new PredictResult();
        Map<String, double[]> map = UHBmodel();

        result.setQSim(map.get("QSim"));
        return result;
    }
}